package com.fare.taluo.queue;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.dayatang.domain.InstanceFactory;
import com.fare.taluo.application.report.careport.ReportOTADomesticApplication;
import com.fare.taluo.application.report.careport.ReportStaticData;
import com.fare.taluo.application.system.email.EmailSendApplication;
import com.fare.taluo.application.system.email.ReportEmailApplication;
import com.fare.taluo.core.domain.queue.message.QueueEmailMessageEntity;
import com.fare.taluo.util.DateUtils;
import com.fare.taluo.vo.core.TaskInfoEntityVO;
import com.fare.taluo.vo.reportemail.EmailVO;
import com.fare.util.ReportProperties;
@Service
public class ReportOTADomestic {
	@Resource(name ="reportEmailApplication")
	private ReportEmailApplication reportEmailApplication;
	
	
	private List<EmailVO> emailList;
	private String email = null;
	
	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}
	
	public List<EmailVO> getEmailList() {
		return emailList;
	}

	public void setEmailList(List<EmailVO> emailList) {
		this.emailList = emailList;
	}

	public void execute() throws Exception{
		try{
		//获取后台要发送的Email
		if(email==null || email==""){
			emailList=reportEmailApplication.findAllEmail(1);//0表示不接受状态，1表示接受状态
			StringBuffer emailStr=new StringBuffer();
			for(EmailVO emailVo:emailList){
				emailStr.append(","+emailVo.getEmailAddress());
			}
			if(emailStr.length()>1 && emailStr !=null){
				email=emailStr.toString().substring(1);
			}
		}
		
		String filePath =creatExcel();
		if(filePath!=null && StringUtils.isNotBlank(getEmail())){
			sendEmail(filePath,getEmail());
		}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		
	}
	
	public String creatExcel() throws Exception{
		
		//取得配置文件实例
		ReportOTADomesticApplication freightPriceOTAApplication = InstanceFactory.getInstance(ReportOTADomesticApplication.class);
		List<TaskInfoEntityVO> list =findTaskInfoList();
		String path;
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		try {
			path = ReportProperties.getInstance().getSavePath().endsWith("/")
					? ReportProperties.getInstance().getSavePath() :
						ReportProperties.getInstance().getSavePath()+"/";
		
				
				freightPriceOTAApplication.createExcelforOTA(list,os);
				if(os!=null){
					String datetype=DateUtils.formatDay(new Date(), "yyyy-MM-dd");
					String fileName ="国航国内航线OTA对比官网报表_"+datetype+".xls";
					String fileEncode = System.getProperty("file.encoding");
					fileName=new String(fileName.getBytes("UTF-8"),fileEncode);
					File f = this.createFile(path, fileName);
					FileUtils.writeByteArrayToFile(f, os.toByteArray());
					return f.getPath();
				}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}finally{
			try {
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
				
	}
	
	public void executeSendEmail() throws Exception{
		Date date =new Date();
		Calendar calendar=Calendar.getInstance();
		calendar.setTime(date);
		String datetype=DateUtils.formatDay(calendar.getTime(), "yyyy-MM-dd");
		//取得配置文件实例
		String path = ReportProperties.getInstance().getSavePath().endsWith("/")
				? ReportProperties.getInstance().getSavePath() :
					ReportProperties.getInstance().getSavePath()+"/";		
		File f =new File(path+"国航国内航线OTA对比官网报表_"+datetype+".xls");
		if(f.exists()){
			sendEmail(f.getPath(),getEmail());
		}else{
			String filePath =creatExcel();
			sendEmail(filePath,getEmail());
		}
	}
	
	public List<TaskInfoEntityVO> findTaskInfoList(){
		List<TaskInfoEntityVO> list =new ArrayList<TaskInfoEntityVO>();
		List<String> listLine =ReportStaticData.getOTADomesticLine();
		for(String line: listLine){
			TaskInfoEntityVO vo =new TaskInfoEntityVO();
			String[] str = line.split("-");
			vo.setFromCity(str[0]);
			vo.setToCity(str[1]);
			list.add(vo);
		}
		return list;
	}
	
	public String sendEmail(String path,String address){
		Date date =new Date();
		Calendar calendar=Calendar.getInstance();
		calendar.setTime(date);
		String datetype=DateUtils.formatDay(calendar.getTime(), "yyyy-MM-dd");
		QueueEmailMessageEntity email = new QueueEmailMessageEntity();
		email.setAttachPath(path);//new String(location.getBytes("UTF-8"),"ISO8859-1")
		email.setBody("<p>您好!<p><p>&nbsp;&nbsp;已生成您需要的国内航线OTA对比官网报表，请查收附件。</p>");
		email.setSubject("国内航线OTA对比官网报表_"+datetype);
		email.setToAddress(address);
		email.setName("国内航线OTA对比官网报表附件");
		InstanceFactory.getInstance(EmailSendApplication.class).save(email);
		return null;
	}
	
	   private File createFile(String filePath, String fileName) throws IOException {
		   try{
			String excelpath = filePath;
			System.out.println("输出路径：" + excelpath);
			// 创建文件
			File path = new File(excelpath);
			if (!path.exists()) {
				path.mkdirs();
			}
			File file = new File(filePath + File.separator + fileName);
			file.createNewFile();
			return file;
		   
	   } catch (IOException e) {
			e.printStackTrace();
			throw e;
		}
	   }
}
		
	

